import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATETIME_FORMAT, DATE_FORMAT} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {injectIntl} from './intl';
import {formatAmount, conventEnumValueToString, formatDateTime, formatPercent, uuid} from '../utils';
import SearchInput from 'Shared/components/SearchInput';
import styles from './style.css';
import DeliveryOrderMultiPanel from './DeliveryOrderMultiPanel';
import Return from '../common/Return';
import {deliveryValidator} from './validator';
import {transportType, currency} from '../Enum';

const FormItem = Form.Item;
class DeliveryPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        details: [],
        showDeliveryOrderMultiPanel: false,
        totalItemCount: [],
        deliveryOrders: []
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onSelectDeliveryOrder = records => {
        const deliveryDetails = [];
        const totalItemCounts = [];
        const deliveryOrders = [];
        const deliveryOrder = records[0];
        const delivery = {
            dealerCode: deliveryOrder.dealerCode,
            sapDeliveryCode: deliveryOrder.sapDeliveryCode,
            partSaleOrderCode: deliveryOrder.partSaleOrderCode,
            partSaleOrderId: deliveryOrder.partSaleOrderId,
            partOrderTypeName: deliveryOrder.partOrderTypeName,
            currency: deliveryOrder.currency,
            transportType: deliveryOrder.transportType,
            totalQuantity: deliveryOrder.totalQuantity,
            totalAmount: deliveryOrder.totalAmount,
            amount: deliveryOrder.amount,
            amountMeetFullRate: deliveryOrder.amountMeetFullRate,
            requiredArrivedDate: deliveryOrder.requiredArrivedDate,
            submitTime: deliveryOrder.submitTime,
        };
        records.forEach(r => {
            deliveryOrders.push({
                deliveryOrderId: r.id,
                rowVersion: r.rowVersion
            });
            r.details.forEach(o => {
                const index = totalItemCounts.findIndex(v => v.partId === o.partId);
                if(index === -1)
                    totalItemCounts.push({
                        partId: o.partId
                    });
                deliveryDetails.push({
                    deliveryOrderId: o.deliveryOrderId,
                    sapDeliveryCode: r.sapDeliveryCode,
                    sapTransferOrderCode: r.sapTransferOrderCode,
                    partSaleOrderId: r.partSaleOrderId,
                    partSaleOrderCode: r.partSaleOrderCode,
                    partId: o.partId,
                    partCode: o.partCode,
                    partName: o.partName,
                    oldPartCode: o.oldPartCode,
                    oldPartName: o.oldPartName,
                    deliveryQuantity: o.deliveryQuantity,
                    price: o.price,
                    totalAmount: o.totalAmount,
                    id: uuid()
                });
            });
        });
        this.setState({
            details: deliveryDetails,
            totalItemCount: totalItemCounts,
            data: delivery,
            deliveryOrders,
            hasOperat: true,
            showDeliveryOrderMultiPanel: false
        });
    }
    onCloseDeliveryOrderMultiPanel = () => {
        this.setState({showDeliveryOrderMultiPanel: false});
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data, deliveryOrders} = this.state;
        const isValid = deliveryValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(deliveryOrders).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickAddBtn = () => {
        this.setState({showDeliveryOrderMultiPanel: true});
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading, totalItemCount} = this.state;
        const validateDeliveryOrderId = !data.deliveryOrderId && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.delivery, this.props.permissions);
        let totalPrice = 0;
        const totalItemCountNum = totalItemCount.length;
        const currentSelectRowkeys = details.map(item => item.sapDeliveryCode);
        if(details.length > 0)
            details.forEach(v => {
                totalPrice += v.price;
            });
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.sapDeliveryCode',
                defaultMessage: '交货单号'
            }),
            dataIndex: 'sapDeliveryCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.sapTransferOrderCode',
                defaultMessage: '调拨单号'
            }),
            dataIndex: 'sapTransferOrderCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partSaleOrderCode',
                defaultMessage: '备件订单号'
            }),
            dataIndex: 'partSaleOrderCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.deliveryQuantity',
                defaultMessage: '交货数量'
            }),
            dataIndex: 'deliveryQuantity',
        }, {
            title: formatMessage({
                id: 'newPanel.column.totalAmount',
                defaultMessage: '金额'
            }),
            dataIndex: 'totalAmount',
        }, {
            title: formatMessage({
                id: 'newPanel.column.oldPartCode',
                defaultMessage: '被替换件编号'
            }),
            dataIndex: 'oldPartCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.oldPartName',
                defaultMessage: '被替换件名称'
            }),
            dataIndex: 'oldPartName',
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '基础信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'postingPanel.operation.partSaleOrderCode',
                                        defaultMessage: '订单编号'
                                    })}
                                    {...FORM_OPTIONS.item}
                                    validateStatus={validateDeliveryOrderId}
                                    required>
                                        <SearchInput
                                            disabled={true}
                                            value={data.partSaleOrderCode}
                                            id={data.partSaleOrderId}
                                            onClickSearchBtn={this.onClickAddBtn} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.dealerCode',
                                        defaultMessage: '总代编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.dealerCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.partOrderTypeName',
                                        defaultMessage: '订单类型'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.partOrderTypeName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.transportType',
                                        defaultMessage: '运输方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(transportType, data.transportType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.totalQuantity',
                                        defaultMessage: '订购数量'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.totalQuantity}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.totalAmount',
                                        defaultMessage: '订单金额'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatAmount(data.totalAmount)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.amount',
                                        defaultMessage: '已发货金额'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatAmount(data.amount)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.amountMeetFullRate',
                                        defaultMessage: '累计金额满足率'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatPercent(data.amountMeetFullRate)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.requiredArrivedDate',
                                        defaultMessage: '要求到货日期'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.requiredArrivedDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.submitTime',
                                        defaultMessage: '提报日期'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.submitTime, DATETIME_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.totalItemCount',
                                        defaultMessage: '开单品种数'
                                    })} {...FORM_OPTIONS.item}>
                                        {totalItemCountNum}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.totalPrice',
                                        defaultMessage: '开单金额'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatAmount(totalPrice)}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.operation.detail',
                            defaultMessage: '交货单信息'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSave',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showDeliveryOrderMultiPanel &&
                        <DeliveryOrderMultiPanel
                            currentSelectRowkeys={currentSelectRowkeys}
                            isDelivery={true}
                            selectKey={data.id}
                            onCancel={this.onCloseDeliveryOrderMultiPanel}
                            onSelect={this.onSelectDeliveryOrder} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

DeliveryPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onDelivery
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: details => dispatch(onDelivery(details)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DeliveryPanel));
